<template>
  <div class="us-cities">
    <el-cascader
        v-model="changedValue"
        :options="options"
        :props="{ expandTrigger: 'hover' }"
        @change="handleChange"></el-cascader>
  </div>
</template>

<script>
import {getCitiesData} from "@/api/packetOrders";

export default {
  props: {
    value: {
      type: Array,
      default() {
        return [];
      },
    },
    district: {
      type: String,
      required: true,
    }
  },
  data() {
    return {
      changedValue: [],
      options: [],
    }
  },
  watch: {
    value(val) {
      this.changedValue = val;
    },
  },
  created() {
    this.changedValue = this.value;
    this.getData();
  },
  methods: {
    getData() {
      getCitiesData({district: this.district})
        .then(res => {
          this.options = res.data.map(item => {
            return {
              value: item.stateName,
              label: item.stateName,
              code: item.stateId,
              children: item.cities.map(child => {
                return {
                  value: child.city,
                  label: child.city,
                }
              })
            }
          });
        })
    },
    handleChange(value) {
      const buyerStateCode = this.options.find(item => item.value === value[0]).code ?? '';
      this.$emit('selectCity', {
        buyerState: value[0],
        buyerCity: value[1],
        buyerStateCode
      });
    },
  }
}
</script>

<style scoped lang="less">

</style>
